<template>
  <div class="admin-users">
    <div class="page-header">
      <h2>用户管理</h2>
      
      <div class="search-box">
        <el-input
          placeholder="搜索用户名/昵称"
          v-model="searchKeyword"
          clearable
          @clear="handleSearch"
          style="width: 200px; margin-right: 10px;">
        </el-input>
        
        <el-select v-model="searchRole" placeholder="用户角色" clearable @change="handleSearch" style="width: 120px; margin-right: 10px;">
          <el-option label="普通用户" :value="1"></el-option>
          <el-option label="管理员" :value="2"></el-option>
          <el-option label="参赛者" :value="3"></el-option>
        </el-select>
        
        <el-select v-model="searchStatus" placeholder="用户状态" clearable @change="handleSearch" style="width: 120px; margin-right: 10px;">
          <el-option label="正常" :value="1"></el-option>
          <el-option label="禁用" :value="0"></el-option>
        </el-select>
        
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        
        <el-dropdown @command="handleSizeChange" style="margin-left: 10px;">
          <el-button type="text">
            表格密度 <i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="medium">默认</el-dropdown-item>
            <el-dropdown-item command="small">紧凑</el-dropdown-item>
            <el-dropdown-item command="mini">迷你</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>
    
    <el-table
      :data="userList"
      border
      :size="tableSize"
      v-loading="loading"
      fit
      style="width: 100%; margin-top: 20px;">
      <el-table-column prop="id" label="ID" width="50"></el-table-column>
      <el-table-column prop="username" label="用户名" width="90"></el-table-column>
      <el-table-column prop="nickname" label="昵称" width="90"></el-table-column>
      <el-table-column prop="avatar" label="头像" width="60">
        <template slot-scope="scope">
          <el-avatar :size="28" :src="scope.row.avatar || defaultAvatar"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="auto" min-width="300"></el-table-column>
      <el-table-column prop="phone" label="手机号" min-width="110"></el-table-column>
      <el-table-column prop="role" label="角色" min-width="80">
        <template slot-scope="scope">
          <el-tag :type="getRoleTagType(scope.row.role)" size="mini">
            {{ getRoleText(scope.row.role) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" min-width="70">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'info'" size="mini">
            {{ scope.row.status === 1 ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="注册时间" min-width="110" align="center">
        <template slot-scope="scope">
          <span class="date-column">{{ formatDateTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" align="center">
        <template slot-scope="scope">
          <div class="action-buttons-container">
            <el-tooltip content="编辑" placement="top">
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit"
                circle
                @click="handleEdit(scope.row)">
              </el-button>
            </el-tooltip>
            <el-tooltip :content="scope.row.status === 1 ? '禁用' : '启用'" placement="top">
              <el-button
                v-if="scope.row.status === 1"
                size="mini"
                type="warning"
                icon="el-icon-lock"
                circle
                @click="handleDisable(scope.row)">
              </el-button>
              <el-button
                v-else
                size="mini"
                type="success"
                icon="el-icon-unlock"
                circle
                @click="handleEnable(scope.row)">
              </el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top" v-if="scope.row.id !== currentUserId">
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                circle
                @click="handleDelete(scope.row)">
              </el-button>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
    </el-table>
    
    <div class="pagination" v-if="total > 0">
      <el-pagination
        background
        @current-change="handleCurrentChange"
        @size-change="handlePageSizeChange"
        :current-page.sync="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
    
    <!-- 空数据显示 -->
    <el-empty v-if="!loading && userList.length === 0" description="暂无用户数据" :image-size="200">
      <el-button type="primary" @click="fetchUsers">重新加载</el-button>
    </el-empty>
    
    <!-- 编辑用户对话框 -->
    <el-dialog title="编辑用户" :visible.sync="editDialogVisible" width="500px">
      <el-form :model="editForm" :rules="userRules" ref="editForm" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="editForm.nickname"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="editForm.role" placeholder="请选择角色">
            <el-option label="普通用户" :value="1"></el-option>
            <el-option label="管理员" :value="2"></el-option>
            <el-option label="参赛者" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择状态">
            <el-option label="正常" :value="1"></el-option>
            <el-option label="禁用" :value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEdit" :loading="submitting">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex'

export default {
  name: 'AdminUsers',
  data() {
    // 邮箱验证
    const validateEmail = (rule, value, callback) => {
      if (value && !/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(value)) {
        return callback(new Error('请输入正确的邮箱地址'))
      }
      callback()
    }
    // 手机号验证
    const validatePhone = (rule, value, callback) => {
      if (value && !/^1[3-9]\d{9}$/.test(value)) {
        return callback(new Error('请输入正确的手机号码'))
      }
      callback()
    }
    
    return {
      userList: [],
      loading: false,
      currentPage: 1,
      pageSize: 20,
      total: 0,
      searchKeyword: '',
      searchRole: '',
      searchStatus: '',
      defaultAvatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
      editDialogVisible: false,
      submitting: false,
      editForm: {
        id: '',
        username: '',
        nickname: '',
        email: '',
        phone: '',
        role: 1,
        status: 1
      },
      userRules: {
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        email: [
          { validator: validateEmail, trigger: 'blur' }
        ],
        phone: [
          { validator: validatePhone, trigger: 'blur' }
        ],
        role: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      },
      tableSize: 'small'
    }
  },
  computed: {
    ...mapState({
      currentUserId: state => state.user?.userId || state.userInfo?.id || null
    })
  },
  created() {
    this.fetchUsers()
  },
  methods: {
    async fetchUsers() {
      this.loading = true
      try {
        const params = {
          page: this.currentPage,
          pageSize: this.pageSize,
          keyword: this.searchKeyword,
          role: this.searchRole,
          status: this.searchStatus
        }
        console.log('Fetching users with params:', params);
        
        // Direct check of the API using Fetch API for comparison
        try {
          const url = new URL('/api/users/page', window.location.origin);
          Object.keys(params).forEach(key => 
            params[key] !== '' && params[key] != null && url.searchParams.append(key, params[key])
          );
          console.log('Testing direct fetch from:', url.toString());
          const fetchResponse = await fetch(url.toString());
          const fetchData = await fetchResponse.json();
          console.log('Direct fetch response:', fetchData);
        } catch (fetchError) {
          console.error('Direct fetch test failed:', fetchError);
        }
        
        // Original Axios request
        const res = await this.$http.get('/users/page', { params });
        console.log('Axios Response:', res);
        
        if (res.data.code === 1) {
          console.log('User data:', res.data.data);
          
          // Defensive checks for the data structure
          if (!res.data.data) {
            console.error('Data is missing in response:', res.data);
            this.$message.error('返回数据缺失');
            this.userList = [];
            this.total = 0;
            return;
          }
          
          if (!Array.isArray(res.data.data.records)) {
            console.error('Records is not an array:', res.data.data);
            this.$message.error('返回数据格式不正确');
            this.userList = [];
            this.total = 0;
            return;
          }
          
          console.log('Records:', res.data.data.records);
          this.userList = res.data.data.records;
          this.total = res.data.data.total || 0;
          
          if (this.userList.length === 0 && this.currentPage > 1) {
            // If current page is empty but we're not on first page,
            // go back to previous page
            this.currentPage -= 1;
            this.fetchUsers();
            return;
          }
        } else {
          console.error('API Error:', res.data);
          this.$message.error(res.data.msg || '获取用户列表失败')
          this.userList = [];
          this.total = 0;
        }
      } catch (error) {
        console.error('Exception when fetching users:', error);
        this.$message.error('获取用户列表失败: ' + (error.message || '未知错误'))
        this.userList = [];
        this.total = 0;
      } finally {
        this.loading = false
      }
    },
    handleSearch() {
      this.currentPage = 1
      this.fetchUsers()
    },
    handleCurrentChange(page) {
      this.currentPage = page
      this.fetchUsers()
    },
    handleEdit(row) {
      this.editForm = {
        id: row.id,
        username: row.username,
        nickname: row.nickname,
        email: row.email,
        phone: row.phone,
        role: row.role,
        status: row.status
      }
      this.editDialogVisible = true
    },
    submitEdit() {
      this.$refs.editForm.validate(async valid => {
        if (valid) {
          this.submitting = true
          try {
            const res = await this.$http.put('/users', this.editForm)
            if (res.data.code === 1) {
              this.$message.success('修改成功')
              this.editDialogVisible = false
              this.fetchUsers()
            } else {
              this.$message.error(res.data.msg || '修改失败')
            }
          } catch (error) {
            console.error('修改用户失败', error)
            this.$message.error('修改失败，请稍后重试')
          } finally {
            this.submitting = false
          }
        }
      })
    },
    handleDisable(row) {
      this.$confirm(`确定要禁用用户"${row.username}"吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const res = await this.$http.put('/users/status', {
            id: row.id,
            status: 0
          })
          if (res.data.code === 1) {
            this.$message.success('禁用成功')
            this.fetchUsers()
          } else {
            this.$message.error(res.data.msg || '操作失败')
          }
        } catch (error) {
          console.error('禁用用户失败', error)
          this.$message.error('操作失败')
        }
      }).catch(() => {})
    },
    handleEnable(row) {
      this.$confirm(`确定要启用用户"${row.username}"吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success'
      }).then(async () => {
        try {
          const res = await this.$http.put('/users/status', {
            id: row.id,
            status: 1
          })
          if (res.data.code === 1) {
            this.$message.success('启用成功')
            this.fetchUsers()
          } else {
            this.$message.error(res.data.msg || '操作失败')
          }
        } catch (error) {
          console.error('启用用户失败', error)
          this.$message.error('操作失败')
        }
      }).catch(() => {})
    },
    handleDelete(row) {
      if (row.id === this.currentUserId) {
        return this.$message.warning('不能删除当前登录用户')
      }
      
      this.$confirm(`确定要删除用户"${row.username}"吗？该操作不可恢复！`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(async () => {
        try {
          const res = await this.$http.delete(`/users/${row.id}`)
          if (res.data.code === 1) {
            this.$message.success('删除成功')
            this.fetchUsers()
          } else {
            this.$message.error(res.data.msg || '删除失败')
          }
        } catch (error) {
          console.error('删除用户失败', error)
          this.$message.error('删除失败')
        }
      }).catch(() => {})
    },
    formatDateTime(time) {
      if (!time) return ''
      const date = new Date(time)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      
      return `${month}-${day} ${hours}:${minutes}`
    },
    getRoleTagType(role) {
      switch (role) {
        case 2:
          return 'danger'
        case 3:
          return 'warning'
        default:
          return 'primary'
      }
    },
    getRoleText(role) {
      switch (role) {
        case 2:
          return '管理员'
        case 3:
          return '参赛者'
        default:
          return '普通用户'
      }
    },
    handleSizeChange(command) {
      this.tableSize = command
    },
    handlePageSizeChange(newSize) {
      this.pageSize = newSize
      this.fetchUsers()
    }
  }
}
</script>

<style scoped>
.admin-users {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #34495e;
  font-size: 24px;
}

.search-box {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

/* Table cell styling */
/deep/ .el-table .cell {
  word-break: break-word;
  line-height: 1.4;
  padding-top: 3px;
  padding-bottom: 3px;
  padding-left: 5px;
  padding-right: 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/deep/ .el-table--mini .cell {
  padding-top: 1px;
  padding-bottom: 1px;
  line-height: 1.3;
}

/deep/ .el-table--mini td, 
/deep/ .el-table--mini th {
  padding: 4px 0;
}

/deep/ .el-table .el-table__row {
  height: 40px;
}

/deep/ .el-table--mini .el-table__row {
  height: 32px;
}

/* Fix for dates */
/deep/ .el-table .cell .date-column {
  white-space: nowrap;
  font-size: 12px;
}

/* Tooltip for operation buttons */
/deep/ .el-tooltip {
  margin: 0 2px;
}

/* Status tag styles */
/deep/ .el-tag {
  font-size: 11px;
  padding: 0 4px;
  height: 20px;
  line-height: 18px;
}

/deep/ .el-tag--mini {
  height: 18px;
  padding: 0 3px;
  line-height: 16px;
  font-size: 10px;
}

/* Compact header styling */
/deep/ .el-table th > .cell {
  font-size: 12px;
  font-weight: bold;
  padding-left: 5px;
  padding-right: 5px;
}

/deep/ .el-table th {
  padding: 5px 0;
  background-color: #f5f7fa;
}

/deep/ .el-table--border th, 
/deep/ .el-table--border td {
  border-right: 1px solid #ebeef5;
}

/deep/ .el-table--border {
  border: 1px solid #ebeef5;
}

/* Action buttons */
.action-buttons-container {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
  flex-wrap: nowrap;
  min-width: 140px;
  margin: 0 auto;
}

.action-buttons-container .el-button--mini {
  padding: 5px;
  margin: 0;
  width: 28px;
  height: 28px;
}

/deep/ .el-button--mini [class^="el-icon-"] {
  font-size: 12px;
}

/* Fix the right column - removing these styles since we're not using fixed right anymore */
/*/deep/ .el-table__fixed-right {
  right: 0 !important;
  height: 100% !important;
  z-index: 10 !important;
  background-color: #fff;
  box-shadow: -2px 0 6px rgba(0, 0, 0, 0.1);
  overflow: visible !important;
}

/deep/ .el-table__fixed-right-patch {
  background-color: #f5f7fa;
  position: absolute;
  top: 0;
  right: 0;
  z-index: 10;
}

/deep/ .el-table__fixed-body-wrapper {
  z-index: 10;
  overflow: visible !important;
}*/

/* Ensure operation buttons are visible */
/*/deep/ .el-table__fixed {
  overflow: visible !important;
}

/deep/ .el-table .el-table__fixed-right .el-table__fixed-header-wrapper,
/deep/ .el-table .el-table__fixed-right .el-table__fixed-body-wrapper {
  right: 0 !important;
  width: 180px !important;
  top: 0;
  overflow: visible !important;
}*/

/deep/ .el-table-column--selection .cell {
  padding-left: 14px;
  padding-right: 14px;
}

/deep/ .el-table th.is-leaf {
  background-color: #f5f7fa;
}

/* Make table fill available space */
/deep/ .el-table {
  width: 100% !important;
  table-layout: fixed;
}

/deep/ .el-table__body {
  width: 100% !important;
}

/deep/ .el-table .el-table__header-wrapper table,
/deep/ .el-table .el-table__body-wrapper table {
  width: 100% !important;
}

/* Force email column to expand */
/deep/ .el-table .cell {
  width: 100%;
}

/deep/ .el-table__body-wrapper {
  overflow-x: hidden !important;
}

/* Fix column stretching */
/deep/ .el-table colgroup col[name="el-table_1_column_5"] {
  width: auto !important;
  min-width: 240px !important;
}

/deep/ .el-table__header col:nth-child(5),
/deep/ .el-table__body col:nth-child(5) {
  width: auto !important;
  flex: 2;
}

/deep/ .el-table {
  display: table;
  border-collapse: collapse;
  table-layout: fixed;
}

/* Ensure no overflow in table */
/deep/ .el-table__body-wrapper {
  overflow-x: auto !important;
}

/* Distribute column widths */
/deep/ .el-table colgroup {
  display: table-row-group;
}

/deep/ .el-table__body, 
/deep/ .el-table__header {
  table-layout: fixed !important;
  width: 100% !important;
}
</style> 